package network

import (
	"math"
)

// 模拟c#中BinaryWriter
type BytesWriter struct {
	buf []byte
}

func NewBytesWriter() *BytesWriter { return &BytesWriter{buf: make([]byte, 0, 1024)} }

func (w *BytesWriter) Len() int {
	return len(w.buf)
}

func (w *BytesWriter) Bytes() []byte {
	return w.buf
}

func (w *BytesWriter) WriteByte(b byte) {
	w.buf = append(w.buf, b)
}

func (w *BytesWriter) WriteUint16(v uint16) {
	w.buf = append(w.buf, byte(v), byte(v>>8))
}

func (w *BytesWriter) WriteUint32(v uint32) {
	w.buf = append(w.buf, byte(v), byte(v>>8), byte(v>>16), byte(v>>24))
}

func (w *BytesWriter) WriteUint64(v uint64) {
	w.buf = append(w.buf, byte(v), byte(v>>8), byte(v>>16), byte(v>>24), byte(v>>32), byte(v>>40), byte(v>>48), byte(v>>56))
}

func (w *BytesWriter) WriteUint8(v uint8) {
	w.WriteByte(byte(v))
}

func (w *BytesWriter) WriteInt8(v int8) {
	w.WriteByte(byte(v))
}

func (w *BytesWriter) WriteInt16(v int16) {
	w.WriteUint16(uint16(v))
}

func (w *BytesWriter) WriteInt32(v int32) {
	w.WriteUint32(uint32(v))
}

func (w *BytesWriter) WriteInt64(v int64) {
	w.WriteUint64(uint64(v))
}

func (w *BytesWriter) WriteFloat32(f float32) {
	w.WriteUint32(math.Float32bits(f))
}

func (w *BytesWriter) WriteFloat64(f float64) {
	w.WriteUint64(math.Float64bits(f))
}

func (w *BytesWriter) WriteBool(v bool) {
	if v {
		w.WriteByte(byte(1))
	} else {
		w.WriteByte(byte(0))
	}
}

func (w *BytesWriter) WriteString(s string) {
	l := byte(len(s))
	w.WriteByte(l)
	if l > 0 {
		w.buf = append(w.buf, s...)
	}
}

func (w *BytesWriter) WriteBytes(b []byte) {
	w.buf = append(w.buf, b...)
}
